package com.envper.common.service.cls.impl;

import com.envper.common.domain.dto.ClassDto;
import com.envper.common.domain.dto.ClassMemberDto;
import com.envper.common.exception.GlobalException;
import com.envper.common.mapper.ClassMapper;
import com.envper.common.service.cls.ClassMemberService;
import com.envper.common.service.cls.ClassService;
import com.envper.common.util.IdUtils;
import com.envper.mysql.base.service.ClassBaseService;
import com.envper.mysql.base.service.ClassDeviceBaseService;
import com.envper.mysql.domain.Status;
import com.envper.mysql.domain.entity.TClass;
import com.envper.mysql.domain.entity.TClassDevice;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ClassServiceImpl implements ClassService {
    private final ClassBaseService classBaseService;
    private final ClassDeviceBaseService classDeviceBaseService;
    private final ClassMemberService classMemberService;
    private final IdUtils idUtils;

    @Override
    public List<ClassDto> getClassList() {
        List<TClass> list = classBaseService.list();
        return ClassMapper.INSTANCE.toClassDtoList(list);
    }

    @Override
    public List<ClassDto> getClassListByUserId(Long userId) {
        List<TClass> tClassList = classBaseService.list(new QueryWrapper().eq("creator", userId));
        return ClassMapper.INSTANCE.toClassDtoList(tClassList);
    }

    @Override
    public void createClass(ClassDto classDto) {
        Long classId = IdUtils.createId();
        Long userId = idUtils.getUserIdByRequest();
        TClass tClass = ClassMapper.INSTANCE.toTClass(classDto);
        tClass.setId(classId);
        tClass.setCreated(LocalDateTime.now());
        tClass.setUpdated(LocalDateTime.now());
        tClass.setCreator(userId);
        boolean save = classBaseService.save(tClass);
        if (!save) throw new GlobalException(Status.CREATEERROR);
        classMemberService.addClassMember(classId, userId);
    }

    @Override
    public ClassDto getClassInfoById(Long id) {
        TClass tClass = classBaseService.getById(id);
        return ClassMapper.INSTANCE.toClassDto(tClass);
    }

    @Override
    public void bindDevice(Long classId, Long deviceId) {
        boolean exists = classDeviceBaseService.exists(new QueryWrapper().eq("class_id", classId).eq("device_id", deviceId));
        if (exists) throw new GlobalException(Status.DeviceBinded);
        TClassDevice tClassDevice = TClassDevice.builder()
                .id(IdUtils.createId())
                .classId(classId)
                .deviceId(deviceId)
                .joined(LocalDateTime.now())
                .build();
        classDeviceBaseService.save(tClassDevice);
    }
}
